package cn.edu.ctbu.config;

import cn.edu.ctbu.interceptor.LoginCheckInterceptor;
import cn.edu.ctbu.utils.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import org.springframework.web.servlet.config.annotation.CorsRegistry;

import java.util.List;

/**
 * @author mijiupro
 */
@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 对所有路径生效
                .allowedOrigins("*") //允许所有源地址
                // .allowedOrigins("https://mijiupro.com","https://mijiu.com ") // 允许的源地址（数组）
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
                .allowedHeaders("*"); // 允许的请求头
    }

    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;


    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/employee/login");
        registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/user/**")
                .excludePathPatterns("/user/user/login").excludePathPatterns("/user/shopStatus")
                .excludePathPatterns("/user/category").excludePathPatterns("/user/dish/category")
                .excludePathPatterns("/user/setmeal/category");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /*
         * 资源映射路径
         * addResourceHandler:访问映射路径
         * addResourceLocations:资源绝对路径
         */
        registry.addResourceHandler("/dishImg/**").addResourceLocations("file:F:\\carry-out-system\\DishImg\\" );
        registry.addResourceHandler("/setmealImg/**").addResourceLocations("file:F:\\carry-out-system\\SetmealImg\\" );
        registry.addResourceHandler("/avatarImg/**").addResourceLocations("file:F:\\carry-out-system\\avatarImg\\" );
    }

    /**
     * 扩展SpringMVC框架的消息转换器
     *
     * @param converters
     */
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器...");
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(new JacksonObjectMapper());
        converters.add(0, converter);
    }
}

